package utils;

import domain.Card;
import domain.Transaction;
import domain.User;

import java.io.*;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Tools {

    /**
     * 根据id获取用户信息
     * @param id
     * @return
     * @throws IOException
     */
    public User getUser(String id) throws IOException {
        String[] users = toStr("user.txt").split(";\n");
        User user = new User();
        boolean flag = true;
        Search s = new Search();
        String res = s.BinSearch(users,Integer.parseInt(id.substring(1)));
        if(res != null){
            flag = false;
            String[] arr = res.split(",");
            user.setUserId(arr[0]);
            user.setName(arr[1]);
            user.setPassword(arr[2]);
            user.setRole(arr[3]);
            user.setPhone(arr[4]);
            user.setEmail(arr[5]);
        }
        if(!flag){
            return user;
        }
        return null;
    }

    /**
     * 存储用户信息
     * @param user
     * @throws IOException
     */
    public void setUser(User user) throws IOException {
        String str = toStr("user.txt");
        FileWriter fw = new FileWriter("src\\files\\user.txt");

        if(str == ""){
            str += user.getUserId()+","+user.getName()+","+user.getPassword()+","+user.getRole()+","+user.getPhone()+","+user.getEmail()+";";
            fw.write(str);
            fw.close();
            return;
        }
        String result = "";
        String[] ids = str.split(";\n");
        boolean flag = true;
        for(int i = 0; i < ids.length; i++){
            if(ids[i].startsWith(user.getUserId()+",")){
                if(i < ids.length-1){
                    System.arraycopy(ids, i+1, ids, i, ids.length-i-1);
                }
                flag = false;
            }
        }
        int length = ids.length;
        if(!flag){
            length--;
        }

        for(int i = 0; i < length; i++){
            result += ids[i]+";\n";
        }
        result += user.getUserId()+","+user.getName()+","+user.getPassword()+","+user.getRole()+","+user.getPhone()+","+user.getEmail()+";\n";
        fw.write(result);
        fw.close();
    }

    public void removeUserById(String id) throws IOException {
        String str = toStr("user.txt");
        FileWriter fw = new FileWriter("src\\files\\user.txt");

        if(str == ""){
            fw.close();
            return;
        }
        String result = "";
        String[] ids = str.split(";\n");
        boolean flag = true;
        for(int i = 0; i < ids.length; i++){
            if(ids[i].startsWith(id+",")){
                if(i < ids.length-1){
                    System.arraycopy(ids, i+1, ids, i, ids.length-i-1);
                }
                flag = false;
            }
        }
        int length = ids.length;
        if(!flag){
            length--;
        }
        for(int i = 0; i < length; i++){
            result += ids[i]+";\n";
        }
        fw.write(result);
        fw.close();
    }

    /**
     * 根据id获取校园卡信息
     * @param id
     * @return
     * @throws IOException
     */
    public Card getCardByUserId(String id) throws IOException {
        String[] users = toStr("card.txt").split(";\n");
        Card card = new Card();
        boolean flag = true;
        Search s = new Search();
        String res = s.BinSearch(users,Integer.parseInt(id.substring(1)));
        if(res != null){
            flag = false;
            String[] arr = res.split(",");
            card.setUserId(arr[0]);
            card.setCardId(arr[1]);
            card.setBalance(Double.parseDouble(arr[2]));
            card.setStatus(arr[3]);
        }
        if(!flag){
            return card;
        }
        return null;
    }

    /**
     * 存储校园卡信息
     * @param card
     * @throws IOException
     */
    public void setCard(Card card) throws IOException {

        String str = toStr("card.txt");
        FileWriter fw = new FileWriter("src\\files\\card.txt");

        if(str == ""){
            str += card.getUserId()+","+card.getCardId()+","+card.getBalance()+","+card.getStatus()+";\n";
            fw.write(str);
            fw.close();
            return;
        }
        String result = "";
        String[] ids = str.split(";\n");
        boolean flag = true;
        for(int i = 0; i < ids.length; i++){
            if(ids[i].startsWith(card.getUserId()+",")){
                if(i < ids.length-1){
                    System.arraycopy(ids, i+1, ids, i, ids.length-i-1);
                }
                flag = false;
            }
        }
        int length = ids.length;
        if(!flag){
            length--;
        }

        for(int i = 0; i < length; i++){
            result += ids[i]+";\n";
        }
        result += card.getUserId()+","+card.getCardId()+","+card.getBalance()+","+card.getStatus()+";\n";
        fw.write(result);
        fw.close();
    }

    public void removeCardByUserId(String userId) throws IOException {

        String str = toStr("card.txt");
        FileWriter fw = new FileWriter("src\\files\\card.txt");


        if(str == ""){
            fw.close();
            return;
        }
        String result = "";
        String[] ids = str.split(";\n");
        boolean flag = true;
        for(int i = 0; i < ids.length; i++){
            if(ids[i].startsWith(userId+",")){
                if(i < ids.length-1){
                    System.arraycopy(ids, i+1, ids, i, ids.length-i-1);
                }
                flag = false;
            }
        }
        int length = ids.length;
        if(!flag){
            length--;
        }
        for(int i = 0; i < length; i++){
            result += ids[i]+";\n";
        }
        fw.write(result);
        fw.close();
    }

    /**
     * 根据id获取交易信息
     * @param cardId
     * @return
     * @throws IOException
     */
    public List<Transaction> getTransaction(String cardId) throws IOException, ParseException {
        File file = new File("src\\files\\transaction.txt");
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        List<String> list = bufferedReader.lines().collect(Collectors.toList());
        List<Transaction> result = new ArrayList<>();

        for (String s : list) {
            String[] arr = s.split("[,;]");
            // 检查分割后的数组长度是否足够
            if (arr.length < 5) continue; // 跳过格式错误的行

            // 首先检查卡号是否匹配
            if (!arr[0].equals(cardId)) {
                continue; // 卡号不匹配则跳过当前记录
            }

            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH:mm:ss");
            LocalDateTime localDateTime = LocalDateTime.parse(arr[4], formatter);

            Transaction transaction = new Transaction();
            transaction.setCardId(arr[0]);
            transaction.setTransactionId(arr[1]);
            transaction.setType(arr[2]);
            transaction.setAmount(Double.parseDouble(arr[3]));
            transaction.setTimestamp(localDateTime);

            result.add(transaction);
        }
        bufferedReader.close(); // 关闭资源
        return result;
    }

    /**
     * 存储交易信息
     * @param transaction
     * @throws IOException
     */
    public void setTransaction(Transaction transaction) throws IOException {
        String str = toStr("transaction.txt");
        FileWriter fw = new FileWriter("src\\files\\transaction.txt");
        // 获取当前日期时间
        LocalDateTime now = LocalDateTime.now();

        // 创建一个自定义格式的 DateTimeFormatter
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH:mm:ss");

        // 使用 format 方法将 LocalDateTime 转换为字符串
        String Time = now.format(formatter);
        str =str+transaction.getCardId()+","+transaction.getTransactionId()+","+ transaction.getType()+","+ transaction.getAmount()+","+ Time+";\n";
        fw.write(str);
        fw.close();
    }

    public String toStr(String fileName) throws IOException {
        File file = new File("src\\files\\"+fileName);
        BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
        String result = bufferedReader.lines().collect(Collectors.toList()).toString();
        result = result.replaceAll(";,", ";\n");
        result = result.replaceAll(" ", "");
        result = result.substring(1,result.length()-1);
        if(result.isBlank()){
            return result;
        }
        return result+"\n";
    }

    public int getID(String name) throws IOException {
        String[] ids = toStr("constant.txt").split(";\n");
        for(String s : ids){
            if(s.startsWith(name+"=")){
                String[] arr = s.split("=");
                return Integer.parseInt(arr[1]);
            }
        }
        return -1;
    }
    public void setID(String name, int id) throws IOException {
        String str = toStr("constant.txt");
        FileWriter fw = new FileWriter("src\\files\\constant.txt");
        String result = "";
        if(str == ""){
            result += name+"="+id+";";
            fw.write(result);
            fw.close();
            return;
        }
        String[] ids = str.split(";\n");

        boolean flag = true;
        for(int i = 0; i < ids.length; i++){
            if(ids[i].startsWith(name+"=")){
                if(i < ids.length-1){
                    System.arraycopy(ids, i+1, ids, i, ids.length-i-1);
                }
                flag = false;
            }
        }
        int length = ids.length;
        if(!flag){
            length--;
        }

        for(int i = 0; i < length; i++){
            result += ids[i]+";\n";
        }
        result += name+"="+id+";\n";
        fw.write(result);
        fw.close();
    }
}